package com.vhall.component.service.data.utils;

import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * export utils：针对标题只有一行的文件
 *
 * @author guoxin.wang
 * @date 2021-07-13 11:30
 */
@Slf4j
public class ExportUtil {

    private static final String CSV = "csv";

    private static final String XLS = "xls";

    private static final String XLSX = "xlsx";

    public static ThreadLocal<ExcelWriter> EXCEL_LOCAL = new ThreadLocal<>();

    public static ThreadLocal<BufferedWriter> CSV_LOCAL = new ThreadLocal<>();

    /**
     * 创建文件并写入标题行
     *
     * @param filePath   文件的地址
     * @param fileType   文件的类型（后缀）
     * @param headerData 标题数据
     * @throws IOException io exception
     */
    public static void writeHeader(String filePath, String fileType, List<String> headerData) throws IOException {
        if (CSV.equals(fileType)) {
            writeHeaderOfCsv(filePath, fileType, headerData);
        } else if (XLS.equals(fileType) || XLSX.equals(fileType)) {
            ExcelWriter writer = ExcelUtil.getWriter(filePath, "sheet1");
            writer.writeHeadRow(headerData);
            EXCEL_LOCAL.set(writer);
        } else {
            BigExcelWriter bigWriter = ExcelUtil.getBigWriter(filePath);
            bigWriter.writeHeadRow(headerData);
            EXCEL_LOCAL.set(bigWriter);
        }
    }

    private static void writeHeaderOfCsv(String filePath, String fileType, List<String> headerData) throws IOException {
        File csvFile = new File(filePath);
        File parent = csvFile.getParentFile();
        if (parent != null && !parent.exists()) {
            boolean mkdirsFlag = parent.mkdirs();
            if (!mkdirsFlag) {
                log.error("文件夹创建失败！");
                return;
            }
        }
        if (!csvFile.exists()) {
            boolean newFileFlag = csvFile.createNewFile();
            if (!newFileFlag) {
                log.error("文件创建失败！");
                return;
            }
        }
        BufferedWriter csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024);
        CsvUtil.writeRow(headerData, csvWtriter);
        CSV_LOCAL.set(csvWtriter);
    }

    /**
     * 创建文件并写入标题行
     *
     * @param fileType 文件的类型（后缀）
     * @param rowData  行数据
     * @throws IOException io exception
     */
    public static void writeRow2(String fileType, List<Object> rowData) throws IOException {
        if (CSV.equals(fileType)) {
            CsvUtil.writeRow(rowData.stream().map(String::valueOf).collect(Collectors.toList()), CSV_LOCAL.get());
        } else {
            EXCEL_LOCAL.get().writeRow(rowData);
        }
    }

    /**
     * 创建文件并写入标题行
     *
     * @param fileType 文件的类型（后缀）
     * @param rowData  行数据
     * @throws IOException io exception
     */
    public static void writeRow(String fileType, List<String> rowData) throws IOException {
        if (CSV.equals(fileType)) {
            CsvUtil.writeRow(rowData, CSV_LOCAL.get());
        } else {
            EXCEL_LOCAL.get().writeRow(rowData);
        }
    }

    public static void close(String fileType) throws IOException {
        if (CSV.equals(fileType)) {
            CSV_LOCAL.get().flush();
            CSV_LOCAL.get().close();
            CSV_LOCAL.remove();
        } else {
            EXCEL_LOCAL.get().flush();
            EXCEL_LOCAL.get().close();
            EXCEL_LOCAL.remove();
        }
    }

    public static void flush(String fileType) throws IOException {
        if (CSV.equals(fileType)) {
            CSV_LOCAL.get().flush();
        } else if (XLS.equals(fileType) || XLSX.equals(fileType)) {
            EXCEL_LOCAL.get().flush();
        } else {
            // BigExcelWriter的flush方法只能调用一次。
            log.info("调用BigExcelWriter的flush方法。");
        }
    }

}
